﻿window.Address = Backbone.Model.extend({
    urlRoot: 'api/address/',
    url: function () {
        return this.urlRoot;
    }
});

window.City = Backbone.Model.extend({
    OrderID: '',
    Name: '',
    Checked: false
});

window.CityList = Backbone.Collection.extend({
    model: City,
    urlRoot: 'api/province/',
    url: function () {
        return this.urlRoot;
    }
});

window.AddressList = Backbone.Collection.extend({
    model: Address,
    urlRoot: 'api/address/',
    url: function () {
        return this.urlRoot + pageView.getCookieValue('uid');
    }
});

window.AddressListView = Backbone.View.extend({
    el: '#jqt',
    initialize: function () {
        this.template = $('#AddressListTemplate').html();
        this.addressList = new AddressList();
        this.cityList = new CityList();
    },
    events: {
        'click #AddressList #AddressSubmit': 'saveAddressChange',
        'click #hideAddressList ul li': 'changeAddressDetail'
    },
    render: function () {
        var partial = { header: $('#HeaderTemplate').html(), footer: $('#FooterTemplate').html(),
            innerFooter: $('#InnerFooterTemplate').html()
        };
        var data = { hasBack: true, title: "返回", btnListR: [{ name: 'home'}] };
        this.$el.append(Mustache.render(this.template, data, partial));
        var that = this;

        if ($('#hideAddressList').length > 0) {
            $('#AddressList .addresslist').html($('#hideAddressList').show());
            this.setAddressDetail();
            pageView.resizeScroll();
        } else {
            this.fetchAddressList();
        }

        return this;
    },

    fetchAddressList: function () {
        var that = this;
        this.addressList.fetch({
            success: function () {
                var template = $('#AddressListContentTemplate').html();
                $('#AddressList .addresslist').html(Mustache.render(template, { addressList: that.addressList.toJSON() }, []));
                $('#hideAddressList').show();
                var addressid = localStorage.getItem('addressid');
                if (addressid && addressid != '-1') {
                    $('#hideAddressList ul[addressid="' + addressid + '"] input').attr('checked', 'checked');
                } else {
                    $('#hideAddressList ul:first-child input').attr('checked', 'checked');
                }
                that.setAddressDetail();
                pageView.resizeScroll();
            }
        });
    },

    setAddressDetail: function (target) {
        var radio = target || $('#AddressList input[type="radio"]:checked');
        var element = radio.closest('ul');

        var data = {
            recivename: element.attr('recivename'),
            address: element.attr('address'),
            mobile: element.attr('mobile'),
            postcode: element.attr('postcode'),
            email: element.attr('email'),
            tel: element.attr('tel')
        };
        var template = $('#AddressDetailContentTemplate').html();
        $('#AddressList .addressDetail').html(Mustache.render(template, data, []));
        var codes = this.getParentRegionCode(element.attr('regionCode'));
        this.fetchProvinceList(codes);
        pageView.resizeScroll();
    },

    getParentRegionCode: function (code) {
        var codes = [];
        $.ajax({
            url: 'api/region/parentcode/get/',
            type: 'GET',
            data: { childCode: code },
            async: false,
            success: function (res) {
                if (res != "") {
                    codes = res.split(',');
                }
            }
        });
        return codes;
    },

    fetchProvinceList: function (codes) {
        var that = this;
        var selectedCode = codes[0] || '';
        var provinces_local = localStorage.getItem('provinces');
        if (provinces_local == null || provinces_local == '[]') {
            this.cityList.fetch({
                success: function () {
                    var template = $('#CitySelectTemplate').html();
                    _.each(that.cityList.toArray(), function (city) { if (city.get('Code') == selectedCode) city.set('Checked', true);});
                    localStorage.setItem('provinces', JSON.stringify(that.cityList.toJSON()));
                    var data = { city: that.cityList.toJSON() };
                    $('select#address_province').html(Mustache.render(template, data, []));
                    var orderid = $('select#address_province').val();
                    that.fetchCityList(orderid, codes);
                }
            });
        } else {
            var template = $('#CitySelectTemplate').html();
            var citys = JSON.parse(provinces_local);
            _.each(citys, function (city) {
                city.Checked = false;
                if (city['Code'] == selectedCode) city.Checked = true;
            });
            localStorage.setItem('provinces', JSON.stringify(citys));
            var data = { city: JSON.parse(localStorage.getItem('provinces')) };
            $('select#address_province').html(Mustache.render(template, data, []));
            var orderid = $('select#address_province').val();
            that.fetchCityList(orderid, codes);
        }

        $('select#address_province').bind('change', function () {
            $('li.address_area').hide();
            var orderid = $(this).val();
            that.fetchCityList(orderid, codes);
        });

    },

    fetchCityList: function (orderid, codes) {
        var that = this;
        var selectedCode = codes[1] || '';
        this.cityList.url = 'api/region/' + (orderid || 0);
        this.cityList.fetch({
            success: function () {
                var template = $('#CitySelectTemplate').html();
                _.each(that.cityList.toArray(), function (city) {
                    if (city.get('Code') == selectedCode) city.set('Checked', true);
                });
                var data = { city: that.cityList.toJSON() };
                $('select#address_city').html(Mustache.render(template, data, []));
                $('li.address_city').show();
                var orderid = $('select#address_city').val();
                that.fetchAreaList(orderid, codes);
                pageView.resizeScroll();
            }
        });

        $('select#address_city').bind('change', function () {
            var orderid = $(this).val();
            that.fetchAreaList(orderid, codes);
        });

    },

    fetchAreaList: function (orderid, codes) {
        var that = this;
        var selectedCode = codes[2] || '';
        this.cityList.url = 'api/region/' + (orderid || 0);
        this.cityList.fetch({
            success: function () {
                var template = $('#CitySelectTemplate').html();
                _.each(that.cityList.toArray(), function (city) {
                    if (city.get('Code') == selectedCode) city.set('Checked', true);
                });
                var data = { city: that.cityList.toJSON() };
                $('select#address_area').html(Mustache.render(template, data, []));
                $('li.address_area').show();
                pageView.resizeScroll();
            }
        });
    },


    changeAddressDetail: function (e) {
        var target = $(e.currentTarget);
        this.setAddressDetail(target.find('input[type="radio"]'));
        pageView.resizeScroll();
    },

    validation: function () {
        $('#where_error').text(''); $('#name_error').text(''); $('#mobile_error').text('');
        $('#tel_error').text(''); $('#email_error').text(''); $('#postcode_error').text('');
        var flag = true,
            address = $('#address_where').val(),
            recivename = $('#address_name').val(),
            email = $('#address_email').val(),
            tel = $('#address_tel').val(),
            postcode = $('#address_zip').val(),
            mobile = $('#address_mobile').val();
        if (address == "") { $('#where_error').text('地址不能为空'); flag = false; }
        if (recivename == "") { $('#name_error').text('收货人不能为空'); flag = false; }
        if (mobile == "") { $('#mobile_error').text('联系电话不能为空'); flag = false; }
        if (mobile != "" && (!(/^0{0,1}(1)[0-9]{10}$/.test(mobile)))) { $('#mobile_error').text('手机号码格式错误'); flag = false; }
        if (tel != "" && (!(/^\d{11}$/.test(tel)))) { $('#tel_error').text('电话号码带区号为11位数字'); flag = false; }
        if (email == "") { $('#email_error').text('Email不能为空'); flag = false; }
        if (email != "" && !(/^[a-zA-Z0-9]+@[a-zA-Z0-9]+.[a-z][a-z.]{2,8}$/.test(email))) { $('#email_error').text('Email格式错误'); flag = false; }
        if (postcode != "" && !/^[1-9]\d{5}$/.test(postcode)) { $('#postcode_error').text('邮政编码格式错误'); flag = false; }
        return flag;
    },

    isChanged: function () {
        var address = $('#address_where').val().trim(),
            email = $('#address_email').val().trim(),
            postcode = $('#address_zip').val().trim(),
            recivename = $('#address_name').val().trim(),
            tel = $('#address_tel').val().trim(),
            mobile = $('#address_mobile').val().trim();
        var addressOrigin = $('#address_where').attr('originvalue').trim(),
            emailOrigin = $('#address_email').attr('originvalue').trim(),
            postcodeOrigin = $('#address_zip').attr('originvalue').trim(),
            recivenameOrigin = $('#address_name').attr('originvalue').trim(),
            telOrigin = $('#address_tel').attr('originvalue').trim(),
            mobileOrigin = $('#address_mobile').attr('originvalue').trim();
        if (address == addressOrigin && email == emailOrigin && postcode == postcodeOrigin && recivename == recivenameOrigin && mobile == mobileOrigin && tel == telOrigin) {
            return false;
        }
        return true;
    },

    saveAddressChange: function () {
        if (this.validation()) {
            var regionCode = $('select#address_area option:selected').attr('addressCode');
            if (!regionCode) { alert('请先选择地区信息，确保订单正确!'); return; }
            var newaddress = new Address();
            newaddress.set({
                NAME: $('#address_name').val().trim(),
                Email: $('#address_email').val().trim(),
                Address: $('#address_where').val().trim(),
                Postalcode: $('#address_zip').val().trim(),
                Mobile: $('#address_mobile').val().trim(),
                Tel: $('#address_tel').val().trim(),
                Code: regionCode
            });
            if (this.isChanged()) {
                newaddress.save('', '', {
                    success: function (model, res) {
                        if (res && res == 201) {
                            pageView.goBack();
                        } else {
                            pageView.goTo('ErrorPage');
                        }
                        localStorage.setItem('addressid', -1);
                        localStorage.setItem('addressItem', JSON.stringify(newaddress));
                    }
                });
            } else {
                var target = $('#AddressList input[type="radio"]:checked');
                localStorage.setItem('addressid', target.closest('ul').attr('addressid'));
                localStorage.setItem('addressItem', JSON.stringify(newaddress));
                pageView.goBack();
            }
            localStorage.setItem('regionCode', regionCode);
        }
    }

}, {
    renderList: function (list) {
        var template = $('#AddressListContentTemplate').html();
        $('#OrderMake').append(Mustache.render(template, { addressList: list }, []));
        var addressid = localStorage.getItem('addressid');
        if (addressid && addressid != '-1') {
            $('#hideAddressList ul[addressid="' + addressid + '"] input').attr('checked', 'checked');
        } else {
            $('#hideAddressList ul:first-child input').attr('checked', 'checked');
        }
    }
});